<?php

namespace App\Http\Controllers\Admins;

use App\Http\Controllers\AdminController;
use App\Models\AdminMenu;
use App\Models\AppUser;
use App\Models\Banner;
use App\Models\SystemFile;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class Home extends AdminController
{
    public function test(Request $request)
    {

    }
    /**
     * 后台登录图形验证码
     * @param CaptchaBuilder $builder
     * @return mixed
     */
    public function captcha(CaptchaBuilder $builder)
    {
        $builder->build(140,40);

        Session::put('captcha',$builder->getPhrase());

        return $this->ReturnSuccessInfo($builder->inline());
    }

    /**
     * 后台登录
     * @param Request $request
     * @return mixed|\Symfony\Component\HttpFoundation\ParameterBag|null
     */
    public function login(Request $request)
    {
        $post = $request->all();

        $validator = Validator::make($post,[
            'username'  => 'required',
            'password'  => 'required',
            'vercode'   => 'required',
        ]);

        if ($validator->fails()){
            return $this->ReturnFailed(1,$validator->errors());
        }

        if (strtolower(Session::get('captcha')) != strtolower($post['vercode'])){
            //return $this->ReturnErrorInfo(2);
        }

        if (! $token = $this->auth()->attempt($request->only(['username','password']))){

            return $this->ReturnErrorInfo(1);
        }

        return $this->ReturnSuccessInfo([
            'username'      => $request->username,
            'nickname'      => $this->auth()->user()->nickname,
            'access_token'  => $token,
            'token_type'    => 'bearer',
            'expires_in'    => $this->auth()->factory()->getTTL() * 60,
        ]);
    }

    /**
     * 刷新token
     * @return mixed|\Symfony\Component\HttpFoundation\ParameterBag|null
     */
    public function refresh()
    {
        return $this->ReturnSuccessInfo([
            'token' =>$this->auth()->resresh(),
        ]);
    }

    /**
     * 导航栏
     * @return mixed
     */
    public function menu()
    {
        $menu = AdminMenu::orderBy('sort','desc')->get()->toArray();

        $user = $this->auth()->user();

        $role = $user->role;

        if (!$role->is_admin && !$role->limit){
            return $this->ReturnErrorInfo(3);  //无权限
        }

        $data = [];
        if ($role->is_admin) {

            foreach ($menu as $key=>$item){

                if ($item['parent']){

                    $data[$item['parent']]['list'][] = $item;
                }else{
                    $item['list'] = [];
                    $data[$item['id']] = $item;

                }
            }

        }else{

            foreach ($menu as $key=>$item){

                if ($item['parent']){
                    if (in_array($data[$item['parent']]['name'].'.'.$item['name'],$role->limit)){
                        $data[$item['parent']]['list'][] = $item;
                    }

                }else{
                    $item['list'] = null;
                    $data[$item['id']] = $item;

                }
            }

        }

        return $this->ReturnSuccessInfo($data);
    }

    public function banner(Request $request)
    {
        $elem = Banner::latest();

        $data = $elem->paginate($request->input('limit',10));

        return $this->ReturnPage($data);
    }

    public function bannerPost(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'    => 'required|integer',
            'name'  => 'required',
            'image' => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        Banner::updateOrCreate(['id'=>$post['id']],$post);

        return $this->ReturnSuccessInfo();
    }

    public function bannerShow(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'    => 'required|integer',
            'show'  => 'required|boolean',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        $banner = Banner::find($post['id']);
        $banner->show = $post['show'];
        $banner->save();

        return $this->ReturnSuccessInfo();
    }

    public function bannerDelete(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'    => 'required|exists:banners,id',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        Banner::destroy($post['id']);

        return $this->ReturnSuccessInfo();
    }

    public function user(Request $request)
    {
        $elem = AppUser::latest();

        $data = $elem->paginate($request->input('limit',10));

        return $this->ReturnPage($data);
    }

    public function userPost(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'        => 'required|integer',
            'mobile'    => 'required|integer',
            'nickname'  => 'required',
            'icon'      => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        AppUser::updateOrCreate(['id'=>$post['id']],$validator->validated());

        return $this->ReturnSuccessInfo();
    }

    public function userRecharge(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'        => 'required|integer',
            'amount'    => 'required|numeric',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        $user = AppUser::find($post['id']);
        $user->balance = $user->balance + $post['amount'];
        $user->save();

        return $this->ReturnSuccessInfo();
    }


    /**
     * 文件列表
     * @param Request $request
     * @return mixed|\Symfony\Component\HttpFoundation\ParameterBag|null
     */
    public function files(Request $request)
    {
        $elem = SystemFile::orderBy('id','desc');

        $data = $elem->paginate($request->input('num','10'));

        $data->transform(function ($item){

            return $item;
        });

        return $this->ReturnPage($data);
    }

    /**
     * 文件上传
     * @param Request $request
     * @return mixed|\Symfony\Component\HttpFoundation\ParameterBag|null
     */
    public function upload(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'image' => 'sometimes|required|image|max:1024',
            'file'  => 'sometimes|required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        if ($request->hasFile('image')){
            $file = $request->file('image');

            if ($file->isValid()){

                $path = $file->store('images'.DIRECTORY_SEPARATOR.date('Ymd'),'public');
            }
        }elseif ($request->hasFile('file')){

            $file = $request->file('file');

            if ($file->isValid()){

                $path = $file->storeAs('files'.DIRECTORY_SEPARATOR.date('Ymd'),uniqid().'.'.$file->getClientOriginalExtension(),'public');
            }

        }else{

            return $this->ReturnFailed(1);
        }

        $info = pathinfo($path);

        $row = SystemFile::create([
            'name'  => $info['filename'],
            'path'  => $path,
            'url'   => Storage::url($path),
            'size'  => $file->getSize(),
            'mime'  => $file->getMimeType(),
        ]);

        return $this->ReturnSuccessInfo([
            'id'    => $row->id,
            'src'   => $row->url,
        ]);
    }


}
